package com.zwh;


import jdk.internal.util.xml.impl.ReaderUTF8;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;


public class test {
    public static void main(String[] args) throws IOException {
        Socket socket = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            //创建一个连接某个服务端的 Socket 对象
            socket = new Socket("localhost", 6666);
            //先查看下socket状态,以方便理解之后的shutdownInput和shutdownOutput
            lookSocketState(socket);
            //从Socket中拿到输出流往服务端发送数据
            outputStream = socket.getOutputStream();
            //向服务器发送一段字符信息,由于TCP是通过流来进行传输的,所以需要先转换为字节,字节采用UTF-8方式进行编码(这意味着服务器需要同样适用UTF-8进行解码)
            outputStream.write("客户端往服务端发送的消息".getBytes(StandardCharsets.UTF_8));
            //调用Socket对象 shutdownOutput 方法通知服务端数据发送完毕
            socket.shutdownOutput();
            System.out.println("socket.isOutputShutdown() = " + socket.isOutputShutdown());
            //从Socket中拿到输入流获取服务端回馈的数据
            inputStream = socket.getInputStream();
            //为了方便直接使用缓冲流阅读了,如果不懂相关知识请先去补充IO知识
            BufferedReader bufferedReader = new BufferedReader(new ReaderUTF8(inputStream));
            String msg = bufferedReader.readLine();
            while (msg != null) {
                System.out.println(msg);
                msg = bufferedReader.readLine();
            }
            //调用Socket对象对象 shutdownInput 方法通知服务端数据接收完毕
            socket.shutdownInput();
            System.out.println("socket.isInputShutdown() = " + socket.isInputShutdown());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流+关闭Socket对象(关闭网络资源)
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void lookSocketState(Socket socket){
        //查看socket状态
        System.out.println("socket.isInputShutdown() = " + socket.isInputShutdown());
        System.out.println("socket.isBound() = " + socket.isBound());
        System.out.println("socket.isClosed() = " + socket.isClosed());
        System.out.println("socket.isConnected() = " + socket.isConnected());
        System.out.println("socket.isOutputShutdown() = " + socket.isOutputShutdown());
    }



}
